import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: jzj
 * Date: 2024-02-20
 * Time: 16:34
 */



public class test3 {
    public static void main(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要查询的学号: ");
        int studentId = scanner.nextInt();

        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/tmpdata?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("12345");

        Connection connection = dataSource.getConnection();

        // 这里同样可以包含一些占位符.
        String sql = "select * from student where id = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1, studentId);

        // 执行查询操作, 要使用 executeQuery. 返回值是一个 ResultSet 类型的对象. 表示了一个 "表格"
        ResultSet resultSet = statement.executeQuery();

        // 遍历结果集合
        while (resultSet.next()) {
            // 获取到这一行的 学号 列
            int id = resultSet.getInt("id");
            // 获取到这一行的 姓名 列
            String name = resultSet.getString("name");
            System.out.println("id: " + id + ", name: " + name);
        }

        // 释放资源.
        resultSet.close();
        statement.close();
        connection.close();
    }
}
